<template>
  <el-card>
    <template #header>
      <div class="card-header">
        <span>Dictionary Types Management</span>
      </div>
    </template>

    <!-- Search Form -->
    <el-form :inline="true" :model="searchParams" @submit.prevent="search">
      <el-form-item label="Name">
        <el-input v-model="searchParams.dictName" placeholder="Name" />
      </el-form-item>
      <el-form-item label="Type">
        <el-input v-model="searchParams.dictType" placeholder="Type" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="search">Search</el-button>
      </el-form-item>
    </el-form>

    <el-button type="primary" @click="openAddModal" style="margin-bottom: 15px;">Add Type</el-button>

    <!-- Table -->
    <el-table :data="dictTypes" stripe style="width: 100%">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="dictName" label="Name" />
      <el-table-column prop="dictType" label="Type" />
      <el-table-column prop="status" label="Status">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
            {{ scope.row.status === 1 ? 'Enabled' : 'Disabled' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="Remark" />
      <el-table-column label="Actions" width="180">
        <template #default="scope">
          <el-button size="small" @click="openEditModal(scope.row)">Edit</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row.id)">Delete</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- Pagination -->
    <el-pagination
      background
      layout="prev, pager, next, total"
      :total="pagination.total"
      :current-page="pagination.pageNum"
      :page-size="pagination.pageSize"
      @current-change="handlePageChange"
      style="margin-top: 15px; justify-content: flex-end;"
    />

    <!-- Add/Edit Dialog -->
    <el-dialog v-model="showModal" :title="isEditMode ? 'Edit Dictionary Type' : 'Add Dictionary Type'" width="500px">
      <el-form :model="currentItem" label-width="80px">
        <el-form-item label="Name">
          <el-input v-model="currentItem.dictName" required />
        </el-form-item>
        <el-form-item label="Type">
          <el-input v-model="currentItem.dictType" required :disabled="isEditMode" />
        </el-form-item>
        <el-form-item label="Status">
          <el-switch
            v-model="currentItem.status"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <el-form-item label="Remark">
          <el-input type="textarea" v-model="currentItem.remark" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeModal">Cancel</el-button>
          <el-button type="primary" @click="handleSubmit">Confirm</el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { useDict } from '~/composables/useDict';
import type { DictType } from '~/types/Dict';
import { ElMessageBox, ElNotification } from 'element-plus';

const { getDictTypePage, addDictType, updateDictType, deleteDictType } = useDict();

const dictTypes = ref<DictType[]>([]);
const pagination = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0,
});
const searchParams = reactive({
  dictName: '',
  dictType: '',
});

const showModal = ref(false);
const isEditMode = ref(false);
const initialItem: DictType = { dictName: '', dictType: '', status: 1, remark: '' };
const currentItem = ref<DictType>({ ...initialItem });

const fetchDictTypes = async () => {
  const params = { pageNum: pagination.pageNum, pageSize: pagination.pageSize, ...searchParams };
  const res = await getDictTypePage(params);
  if (res && res.success) {
    dictTypes.value = res.data.records;
    pagination.total = res.data.total;
  }
};

onMounted(fetchDictTypes);

const search = () => {
  pagination.pageNum = 1;
  fetchDictTypes();
};

const handlePageChange = (page: number) => {
  pagination.pageNum = page;
  fetchDictTypes();
};

const openAddModal = () => {
  isEditMode.value = false;
  currentItem.value = { ...initialItem };
  showModal.value = true;
};

const openEditModal = (item: DictType) => {
  isEditMode.value = true;
  currentItem.value = { ...item };
  showModal.value = true;
};

const closeModal = () => {
  showModal.value = false;
};

const handleSubmit = async () => {
  const action = isEditMode.value ? updateDictType : addDictType;
  const res = await action(currentItem.value);
  if (res && res.success) {
    ElNotification({
      title: 'Success',
      message: isEditMode.value ? 'Updated successfully' : 'Added successfully',
      type: 'success',
    });
    closeModal();
    fetchDictTypes();
  } else {
     ElNotification({
      title: 'Error',
      message: res.message || 'Operation failed',
      type: 'error',
    });
  }
};

const handleDelete = async (id?: number) => {
  if (!id) return;
  try {
    await ElMessageBox.confirm('This will permanently delete the item. Continue?', 'Warning', {
      confirmButtonText: 'OK',
      cancelButtonText: 'Cancel',
      type: 'warning',
    });
    const res = await deleteDictType(id);
    if (res && res.success) {
      ElNotification({
        title: 'Success',
        message: 'Deleted successfully',
        type: 'success',
      });
      fetchDictTypes();
    } else {
      ElNotification({
        title: 'Error',
        message: res.message || 'Delete failed',
        type: 'error',
      });
    }
  } catch {
    // Catch cancellation of confirmation box
  }
};
</script> 